import request from '@/utils/request';

// 定义上传用户相关信息
export interface UploadUser {
  user_id?: number;
  account?: string;
  name?: string;
  avatar?: string;
}

// 定义上传文件相关接口的类型
export interface UploadFile {
  upload_id?: number;
  original_name: string;
  filename: string;
  filepath: string;
  fileurl: string;
  size: number;
  mimetype: string;
  user_id?: number;
  publish_id?: number;
  created_at?: string;
  updated_at?: string;
  upload_user?: UploadUser; // 新增关联的用户信息
  createdAt?: string; // 添加创建时间字段
}

export interface UploadResult {
  upload_id: number;
  original_name: string;
  filename: string;
  filepath: string;
  fileurl: string;
  size: number;
  mimetype: string;
  user_id?: number;
}

// 文件上传
export const uploadFile = (
  formData: FormData, 
  onProgress?: (progress: number) => void
) => {
  return request.post<UploadResult>('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress && progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(progress);
      }
    }
  });
};

// 获取上传文件列表
export const getUploadList = (data?: { keyword?: string; sort_field?: string; sort_order?: string }) => {
  return request.post<UploadFile[]>('/upload/getUploadList', data);
};

// 获取上传文件列表（分页）
export const getUploadListPage = (data: { page?: number; limit?: number; keyword?: string; sort_field?: string; sort_order?: string }) => {
  return request.post<{ list: UploadFile[]; pagination: any }>('/upload/getUploadListPage', data);
};

// 根据ID获取上传文件信息
export const getUploadById = (upload_id: number) => {
  return request.post<UploadFile>(`/upload/getUploadById`, { upload_id });
};

// 删除上传文件
export const deleteUpload = (upload_id: number) => {
  return request.post('/upload/deleteUpload', { upload_id });
};

// 批量删除上传文件
export const batchDeleteUpload = (upload_ids: number[]) => {
  return request.post('/upload/batchDeleteUpload', { upload_ids });
};